package cn.maihe.elg.operation.supports.electronicseal.anne.service.impl;

import cn.maihe.elg.operation.config.AnneSignConfig;
import cn.maihe.elg.operation.config.ElgConfig;
import cn.maihe.elg.operation.config.ImageUploadConfig;
import cn.maihe.elg.operation.model.enums.AuditStatusEnum;
import cn.maihe.elg.operation.model.enums.BidCustomerStatus;
import cn.maihe.elg.operation.model.enums.CustomerAttachmentTypeEnum;
import cn.maihe.elg.operation.repository.entity.BidCustomerDO;
import cn.maihe.elg.operation.repository.entity.CustomerAttachmentDO;
import cn.maihe.elg.operation.repository.entity.CustomerAttachmentDOCondition;
import cn.maihe.elg.operation.repository.entity.OrganizationDO;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.CustomerAttachmentService;
import cn.maihe.elg.operation.supports.electronicseal.anne.AnneServiceName;
import cn.maihe.elg.operation.supports.electronicseal.anne.BaseAnneSignService;
import cn.maihe.elg.operation.supports.electronicseal.anne.EnterpriseStatus;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.base.SecureApiResponse;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.enterprise.EnterpriseCreateRequest;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.enterprise.EnterpriseCreateRequestBody;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.enterprise.vo.EnterpriseResult;
import cn.maihe.elg.operation.supports.electronicseal.anne.utils.annesign.ApiException;
import cn.maihe.framework.starter.mybatis.dao.MybatisDaoImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * @Description 安妮侧创建企业 ：已备案成功的企业才能 创建合同、发起合同签署等操作
 * @Author WJH
 * @Date 2021/08/13
 */
@Slf4j
@Service
public class EnterpriseCreateService extends BaseAnneSignService<EnterpriseCreateRequest, SecureApiResponse> {
    @Resource
    private CustomerAttachmentService customerAttachmentService;

    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private EnterpriseResultQueryService enterpriseResultQueryService;
    @Resource
    private ImageUploadConfig imageUploadConfig;

    public EnterpriseCreateService(AnneSignConfig anneSignConfig, ElgConfig elgConfig) {
        super(anneSignConfig, elgConfig);
    }

    @Override
    protected AnneServiceName serviceName() {
        return AnneServiceName.enterprise_create;
    }

    @Override
    protected EnterpriseCreateRequest buildBaseReq() {
        return super.buildBaseReq();
    }

    public void createBidderEnterprise(Long bidCustomerId,String auditDesc, String legalPersonTel) {

        BidCustomerDO bidCustomer = bidCustomerService.selectById(bidCustomerId);
        List<CustomerAttachmentDO> attachmentList = customerAttachmentService.selectList(CustomerAttachmentDOCondition.builder().andBidderIdEq(bidCustomerId).build());

        //待内部审核|审核不通过后 才能发起 到安妮渠道创建企业
        Integer status = bidCustomer.getStatus();
        BidCustomerStatus bidCustomerStatus = BidCustomerStatus.resolve(status);
        if (bidCustomerStatus != BidCustomerStatus.AUDIT_INNER && bidCustomerStatus != BidCustomerStatus.AUDIT_OUTER && bidCustomerStatus != BidCustomerStatus.AUDIT_FAIL) {
            throw new RuntimeException("投标企业审核状态为[" + bidCustomerStatus.getDesc() + "],暂无法发起创建企业");
        }

        EnterpriseResult result = enterpriseResultQueryService.queryEnterpriseResult(bidCustomer.getBidderCreditCode());
        //不存在则创建
        if (result.getStatus() == EnterpriseStatus.NOT_EXISTS || result.getStatus() == EnterpriseStatus.AUDIT_REJECT) {
            EnterpriseCreateRequestBody body = new EnterpriseCreateRequestBody();
            body.setName(bidCustomer.getBidderName());
            body.setLicenseCode(bidCustomer.getBidderCreditCode());
            body.setLicenseImgBase64(customerAttachmentService.getBase64Str(attachmentList, CustomerAttachmentTypeEnum.TYPE_0));
            body.setIndustryType("TRAVEL");
            body.setLegalPersonName(bidCustomer.getLegalPersonName());
            body.setLegalPersonMobile(legalPersonTel);//bidCustomer.getBidderContactTel());
            body.setLegalPersonCertType("ID_CARD");
            body.setLegalPersonCertNo(bidCustomer.getLegalPersonIdcard());
            body.setLegalPersonCertFrontImgBase64(customerAttachmentService.getBase64Str(attachmentList, CustomerAttachmentTypeEnum.TYPE_3));
            body.setLegalPersonCertBackImgBase64(customerAttachmentService.getBase64Str(attachmentList, CustomerAttachmentTypeEnum.TYPE_2));
            body.setAuthImgBase64(customerAttachmentService.getBase64Str(attachmentList, CustomerAttachmentTypeEnum.TYPE_4));
            body.setSealImgBase64(customerAttachmentService.getBase64Str(attachmentList, CustomerAttachmentTypeEnum.TYPE_5));
            body.setAdditionalAUthImaBase64(customerAttachmentService.getBase64Str(attachmentList, CustomerAttachmentTypeEnum.TYPE_6));
            body.setNotifyEnable("1");
            body.setNotifyUrl(ANNE_NOTIFY_URL);
            //安妮侧的创建企业id可以理解为父企业id，没有则置为空CreatedEnterpriseId
            body.setCreatedEnterpriseId(null);
            body.setCompleteAddress(bidCustomer.getBidderRegAddress());

            EnterpriseCreateRequest request = this.buildBaseReq();
            request.setBody(body);

            try{
                SecureApiResponse response = this.doPost(request);
            }catch(ApiException e){

                //提交创建企业变更投标客户状态为 待第三方审核
                BidCustomerDO updateDO = BidCustomerDO.builder().id(bidCustomer.getId())
                        .status(BidCustomerStatus.AUDIT_FAIL.getStatus())
                        .auditDesc(e.getMessage())
                        .gmtModified(Date.from(Instant.now())).build();
                bidCustomerService.updateById(updateDO);
                return;
            }

            //提交创建企业变更投标客户状态为 待第三方审核
            BidCustomerDO updateDO = BidCustomerDO.builder().id(bidCustomer.getId())
                    .status(BidCustomerStatus.AUDIT_OUTER.getStatus())
                    .legalPersonTel(legalPersonTel)
                    .auditDesc(auditDesc)
                    .gmtModified(Date.from(Instant.now())).build();
            bidCustomerService.updateById(updateDO);

        } else {
            log.warn("投标企业[{}]在安妮证宝中已存在，暂无需再提交创建企业,默认状态为查询返回的状态转换", bidCustomer.getBidderCreditCode());

            Long enterpriseId = result.getEnterpriseId();
            String auditOpinion = result.getAuditDesc();
            /**企业状态，0：待审核，5：审核失败，9：审核通过（详见数据字典：auditStatus）*/
            EnterpriseStatus enterpriseStatus = result.getStatus();
            if (enterpriseStatus == EnterpriseStatus.AUDIT_PASS) {
                status = BidCustomerStatus.NORMAL.getStatus();
                bidCustomer.setStatus(status);
                bidCustomer.setEnterpriseId(enterpriseId);

                bidCustomerService.customerSuccess(bidCustomer);
            } else if (enterpriseStatus == EnterpriseStatus.AUDIT_REJECT) {
                status = BidCustomerStatus.AUDIT_FAIL.getStatus();
            } else if (enterpriseStatus == EnterpriseStatus.AUDITING) {
                status = BidCustomerStatus.AUDIT_OUTER.getStatus();
            }


            BidCustomerDO updateDO = BidCustomerDO.builder().id(bidCustomer.getId()).status(status).auditDesc(auditOpinion)
                    .legalPersonTel(legalPersonTel)
                    .gmtModified(Date.from(Instant.now())).build();
            if (enterpriseId != null) {
                updateDO.setEnterpriseId(enterpriseId);
            }
            MybatisDaoImpl.run().updateById(updateDO);

        }
    }


    /**
     * 安妮渠道创建担保机构企业
     *
     * @param organization
     */
    public void createOrgEnterprise(OrganizationDO organization) {
        Integer status = organization.getAuditStatus();
        AuditStatusEnum auditStatusEnum = AuditStatusEnum.resolve(status);
        if (auditStatusEnum != AuditStatusEnum.AUDIT_OUT) {
            throw new RuntimeException("担保企业审核状态为[" + auditStatusEnum.getLabel() + "],暂无法发起创建企业");
        }
        EnterpriseResult result = enterpriseResultQueryService.queryEnterpriseResult(organization.getCreditCode());
        //不存在则创建
        if (result.getStatus() == EnterpriseStatus.NOT_EXISTS || result.getStatus() == EnterpriseStatus.AUDIT_REJECT) {
            EnterpriseCreateRequestBody body = new EnterpriseCreateRequestBody();
            body.setName(organization.getFullName());
            body.setLicenseCode(organization.getCreditCode());
            body.setLicenseImgBase64(this.getBase64Str(organization.getBusinessLicensePic()));
            body.setIndustryType("TRAVEL");
            body.setLegalPersonName(organization.getLegalName());
            body.setLegalPersonMobile(organization.getContactTel());
            body.setLegalPersonCertType("ID_CARD");
            body.setLegalPersonCertNo(organization.getLegalIdcard());
            body.setLegalPersonCertFrontImgBase64(this.getBase64Str(organization.getLegalIdcardReversePic()));
            body.setLegalPersonCertBackImgBase64(this.getBase64Str(organization.getLegalIdcardPic()));
            body.setAuthImgBase64(this.getBase64Str(organization.getApplyPic()));
            if (StringUtils.isNotBlank(organization.getAuthPic())) {
                body.setAdditionalAUthImaBase64(this.getBase64Str(organization.getAuthPic()));
            }
            body.setNotifyEnable("1");
            body.setNotifyUrl(ANNE_NOTIFY_URL);
            //安妮侧的创建企业id可以理解为父企业id，没有则置为空CreatedEnterpriseId
            body.setCreatedEnterpriseId(null);
            body.setCompleteAddress(organization.getAddress());

            EnterpriseCreateRequest request = this.buildBaseReq();
            request.setBody(body);
            SecureApiResponse response = this.doPost(request);

            //提交创建企业变更投标客户状态为 待第三方审核
            OrganizationDO updateDO = OrganizationDO.builder().id(organization.getId()).auditStatus(AuditStatusEnum.AUDIT_OUT.getValue()).gmtModified(Date.from(Instant.now())).build();
            MybatisDaoImpl.run().updateById(updateDO);

        } else {
            log.warn("担保企业[{}]在安妮证宝中已存在，暂无需再提交创建企业,默认状态为待第三方审核", organization.getFullName());

            Long enterpriseId = result.getEnterpriseId();
            String auditOpinion = result.getAuditDesc();
            EnterpriseStatus enterpriseStatus = result.getStatus();
            /**业务状态**/
            Integer businessStatus = null;
            if (enterpriseStatus == EnterpriseStatus.AUDIT_PASS) {
                status = AuditStatusEnum.AUDITED.getValue();
                businessStatus = 1;
            } else if (enterpriseStatus == EnterpriseStatus.AUDIT_REJECT) {
                status = AuditStatusEnum.AUDIT_REJECT.getValue();
                businessStatus = 0;
            } else if (enterpriseStatus == EnterpriseStatus.AUDITING) {
                status = AuditStatusEnum.AUDIT_OUT.getValue();
            }
            OrganizationDO updateDO = OrganizationDO.builder().id(organization.getId()).gmtModified(Date.from(Instant.now())).build();
            updateDO.setAuditStatus(status);
            updateDO.setBusinessStatus(businessStatus);
            updateDO.setAuditDesc(auditOpinion);
            updateDO.setEnterpriseId(enterpriseId);

            MybatisDaoImpl.run().updateById(updateDO);
        }
    }


    public String getBase64Str(String pic) {
        String baseDir = imageUploadConfig.getPath();
        Path absolutePath = Paths.get(baseDir + pic);
        if (Files.notExists(absolutePath)) {
            throw new RuntimeException("文件不存在[" + absolutePath.toString() + "]");
        }
        try {
            return Base64.getEncoder().encodeToString(Files.readAllBytes(absolutePath));
        } catch (IOException e) {
            throw new RuntimeException("文件转base64异常:" + e.getMessage(), e);
        }
    }


}
